const express = require('express');
const router = express.Router();
const {asyncHandler,getErr} =require("../middleWare/getSentResult");
const adminServer = require('../server/adminServer')
const md5 = require("md5");
const {getR,setR,caseTime,delR, delDB}= require("../server/redisServe");
const { cookieName, apiGetBanner,apigetMeun,avater1} = require('../routerConfig');
const {encrypto} = require("../middleWare/crypt")
const upload = require('../server/uploadServ')
const bannerServe = require('../server/bannerServer')
const homeInfoServer = require('../server/homeInfoServer')
const messageServer = require('../server/messageServer')
const commentServer = require('../server/commentServer')
const blogeServer = require('../server/blogServer')
const blogTypeServer = require('../server/blogTypeServer')
const changeToc = require('../middleWare/toc');
router.post('/login',asyncHandler(async(req,res)=>{
 
    const  { username, password,captch,reLogin,id} = req.body;
    const CResult = await getR(5,id);
    if(!(captch == CResult))  res.status(200).send(getErr("验证码错误",404))
    const result = await adminServer.login(username,md5(password));
    if(!result) {
        
        res.status(200).send(getErr("密码或账号错误",404));
    };
    const rId = result._id;
    const val = encrypto(rId);
    const time = caseTime * 2 * (reLogin == "" ? 0 : reLogin);
    res.cookie(cookieName,val,{
        patch:"/",
        maxAge: time
    });
    await setR(5,rId,'admin',{
        EX:time
    });
    result.token = val;
    delete  result._id;
    return result;
}))
router.get('/whyi',asyncHandler(async (req,res,next)=>{
   
    const result = await adminServer.whyi(req.adminId);
    
    return result;

}))

router.post('/upadmin',asyncHandler(async(req,res,next)=>{


}))
router.post("/logout",asyncHandler(async(req,res,next)=>{

    if(req.adminId){
       await delR(5,req.adminId);
       return '登出成功'
    }else{
        return '登出失败，未找到该账号！'
    }
    
}))
router.post('/upload',upload.single('img'),(req,res,next)=>{
    const url = `/upload/${req.file.filename}`;
    res.send({
      code: 0,
      msg: "",
      data: url,
    });

})
router.post('/upBanner',asyncHandler(async(req,res,next)=>{
    const { _id, thumb,imgUrl } = req.body
    const result = await bannerServe.upBanner(_id,thumb,imgUrl);
    await delR(0,apiGetBanner)
    if(result){
        return true
    }
}))

router.post('/upMeun', asyncHandler( async (req,res,next) => {
    const { Nav , _id, mailto, recrod, icon} = req.body
    if(!(Nav.length >= 4 && _id && mailto && recrod && icon)) return '条件不足，修改失败' 
    const result = await homeInfoServer.upInfo(_id,Nav,mailto,recrod,icon);

    if(result){
        await delR(0,apigetMeun)
        return true 

    } else {
        return "失败"
    } 
}))

router.post('/upAVatar',asyncHandler(async (req,res,next)=>{
    const { _id, name, img, descript } = req.body;
    if(!(_id && name && img && descript)) return '条件不足';
    const result = await homeInfoServer.upAvatar(_id,name,img,descript)
    await delR(0,avater1)
    return result
}))

router.get('/message', asyncHandler(async(req,res,next)=>{
    const {limit, skip} = req.query;
  
    const result = await messageServer.getMessageAdmin(limit,skip);
   
    return result;
}))

router.get('/comment', asyncHandler(async(req,res,next)=>{
    const {limit, skip} = req.query;
    const result = await commentServer.getCommentAdmin(limit,skip);
    
    return result;
}))

router.post('/upCommentShow', asyncHandler( async (req,res,next)=>{

    const { _id, isShow } = req.body
    const result = await commentServer.setCommentShow(_id,isShow)
    await  delDB(6);
    return result;

}))
router.post('/upMessageShow', asyncHandler( async (req,res,next)=>{

    const { _id, isShow } = req.body
    try {
        const result = await messageServer.setMessageShow(_id,isShow)
        await delDB(7);
        return result;
    } catch(e) {
        return e.name
    }
}))
router.post('/delMessage', asyncHandler( async (req,res,next)=>{

    const { _id } = req.body
    try {
        const result = await messageServer.delMessage(_id)
        if(result.deletedCount === 1) {
            await delDB(7)
            return true
        } else {
            return false
        }
    } catch(e) {
        return e.name
    }
}))
router.post('/delComment', asyncHandler( async (req,res,next)=>{

    const { _id } = req.body
    try {
        const result = await commentServer.delComment(_id)
        if(result.deletedCount === 1) {
            delDB(6)
            return true
        } else {
            return false
        }
    } catch(e) {
        return e.name
    }
}))
router.post('/delBlog', asyncHandler( async (req,res,next)=>{

    const { _id,blogType } = req.body
    try {
        const result = await blogeServer.delBlog(_id,blogType)
        if(result.deletedCount === 1) {
            return true
        } else {
            return false
        }
    } catch(e) {
        return e.name
    }
}))

router.post('/delBlogType',asyncHandler(async (req,res,next) =>{
    const { _id } = req.body;
    try {
        const result = await blogTypeServer.delType(_id)
        if(result.deletedCount === 1) {
            return true
        } else {
            return false
        }
    } catch(e) {
        return e.name
    }
}))

router.post('/upBlogType', asyncHandler( async(req,res,next)=>{
    const { _id, name, sum } = req.body
    try{

       const result = await blogTypeServer.upType(_id,name,sum)
       return result
    } catch(e) {
        return e.name
    }
    
} ))

router.post('/addBlog', asyncHandler(async(req,res,next)=>{
   
    const { blog } = req.body
    const changeResult =  changeToc(blog)

    try {
        const result = await blogeServer.addBlog(changeResult);
        return result;

    }catch(e) {
        return e.name
    }

    

}))

router.post('/upBlog',asyncHandler(async(req,res,next)=>{
    const { blog } = req.body
    const { _id, htmlContent,blogType, title, thums, descrition, toch} = changeToc(blog);
    try {
        const result = await blogeServer.upBlog(_id, htmlContent,blogType, title, thums, descrition, toch)
        return result;

    }catch(e) {
        return e.name
    }
    
}))

router.post('/upMeun', asyncHandler(async(req,res,nex)=>{
    const {name, icon, path} = req.body
    
}))



module.exports = router;